% Inport simulation of Cohort, Duration and ML 
% Calculate SVD metrics and difference between them
% deltaSVD_Coh_Dur = coh - dur
% deltaSVD_ML_Dur = ml - dur
% build distribution of deltaSVD1 and deltaSVD2 to see the quantile
clear all
clc

Iteration = 200;
nRatings = 8; % include default
data = zeros(Iteration, nRatings, nRatings);

%Import ML data from R to Matlab
status = openR;
for i = 1: Iteration
putRdata('i',i);

evalR('openfile<-paste("D:\\My Documents\\CIRANO\\db_mySQL\\bootsprob_01\\bootQ_",i,".RData",sep="")');
evalR('load(openfile)')
data (i,:,:) = getRdata('bootP');
evalR('rm(list=ls())');
end
closeR;   
save('D:\My Documents\CIRANO\db_mySQL\bootstrap_cal_ML.mat','data');

%Import Cohort and Duration 
load('D:\My Documents\CIRANO\db_mySQL\bootstrap_cal_cohDur_01_case2.mat','cohStd','durStd');


% SVD
deltaSVD_Coh_Dur = zeros(Iteration,1);
deltaSVD_ML_Dur = zeros(Iteration,1);
for i = 1:Iteration
    
coh(:,:) =  cohStd(i,:,:)./100;
dur(:,:) =  durStd(i,:,:)./100;
ml(:,:)  = data(i,:,:);

SVD_coh = mean(svd(coh-eye(nRatings)));
SVD_dur = mean(svd(dur-eye(nRatings)));
SVD_ml = mean(svd(ml-eye(nRatings)));

deltaSVD_Coh_Dur (i,1)= SVD_coh - SVD_dur;
deltaSVD_ML_Dur (i,1)= SVD_ml - SVD_dur;

end

% the quartiles of deltaSVD_Coh_Dur
quantile_Coh_Dur = quantile(deltaSVD_Coh_Dur,[.01 .025 .05 .50 .95 .975 .99]); 
quantile_ML_Dura = quantile(deltaSVD_ML_Dur,[.01 .025 .05 .50 .95 .975 .99]);
miu_Coh_Dur = mean(deltaSVD_Coh_Dur);
sig_Coh_Dur = std(deltaSVD_Coh_Dur);
miu_ML_Dur = mean(deltaSVD_ML_Dur);
sig_ML_Dur = std(deltaSVD_ML_Dur);
